package com.bird.thread.base.stopthread;

/**
 * @author sijunqiang
 * @data 2021/6/26 14:27
 * @description: 当While 里面放try/catch,导致中断失效。
 */
public class CantInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;

            while (num <= 10000) {
                if (num % 100 == 0 && !Thread.currentThread().isInterrupted()) {
                    System.out.println(num + " 是100的倍数");
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    System.out.println("result: "+ interrupted);
                }
                num++;
                try {
                    // 模拟 线程阻塞时 会造成什么问题。
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        boolean interrupted = thread.isInterrupted();
        System.out.println("before: interrupt= " + interrupted);
        Thread.sleep(5000);
        thread.interrupt();
        boolean interrupted1 = thread.isInterrupted();
        System.out.println("after: " + interrupted1);
    }


    /*
     * 总结： 如果在while里面 有try/catch 那么就会导致这一种情况 既是抛出了异常 但是还是会继续往往下执行的。
     * 是因为：当线程响应中断 便会把线程的interrupt的标记位给清除掉。
     *
     *
     * */
}
